<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/7
 * Time: 15:54
 */

namespace App\Api\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Exceptions\ApiException;
use App\Services\Admin;
use Illuminate\Support\Facades\Cache;
use App\Models\Admin\AdminUser;

class LoginController extends Controller
{
    /**
     * 登录
     * @return array
     * @throws ApiException
     */
    public function login()
    {
        $username = IT('username', true, '请输入用户名');
        $password = IT('password', true, '请输入密码');
        $user = AdminUser::where('username',$username)->first();
        if (!$user){
            return json_error('用户名不存在或用户名错误');
        }
        $md5password = md5($password);
        if ($user && $md5password.$user->encrypt != $user->password.$user->encrypt) {
               return json_error('密码不正确');
        }
        $user = array_merge($user->toArray(), Admin::getPermission($user->role_id));
        $token = md5(date('Ymd') . uniqid());
        $res = Cache::put($token, $user, 1440);
        return json_success('ok', ['token' => $token, 'name' => $user['name'], 'role' => $user['role'],'id'=>$user['id'],  'permissions' => $user['permissions']]);
    }
}